from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth import serializers
from oauth.models import OAuthUser
from oauth.utils import generate_save_user_token


class QQAuthURLView(APIView):
    """提供QQ登录页面网址
       https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
       """

    def get(self, request):
        # 登陆成功以后的跳转地址
        next = request.query_params.get("next")
        if next is None:
            # 如果没有设置，则默认为域名根目录
            next = "/"

        # 使用qqLoginTool工具包里面的方法生成url
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        login_url = oauth.get_qq_url()

        return Response({'login_url': login_url})


class QQAuthUserView(GenericAPIView):
    """
    　　QQ登陆成功后的页面跳转功能
    　　　 GET /oauth/qq/user/?code=xxx&next=xxx
    """
    serializer_class = serializers.QQAuthUserSerializer

    def get(self, request):
        # 1. 获取code授权码
        code = request.query_params.get("code")
        # print(code)
        if code is None:
            return Response({'message': '缺少code授权码'}, status=status.HTTP_400_BAD_REQUEST)

        # 获取可能跳转的路径
        state = request.query_params.get("next")
        if state is None:
            state = "/"

        # 2. 获取QQ登陆的access_token
        # 使用qqLoginTool工具包里面的方法生成url
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=state
        )
        access_token = oauth.get_access_token(code)
        # print(access_token)
        # 3. 根据access_token获取openID
        openid = oauth.get_open_id(access_token)
        # print(openid)

        # 4. 根据openID到数据库中查找是否有对应的QQ登陆用户
        try:
            # 表示不是第一次使用QQ登陆，直接保存登陆状态
            # [先做状态保存，先到数据表中添加一条记录]
            oauth_user = OAuthUser.objects.get(openid=openid)
        except OAuthUser.DoesNotExist:
            # 没有找到openID对应的用户，则表示是第一次使用QQ登陆
            # 让用户进行身份绑定
            # print(generate_save_user_token(openid))
            return Response({
                # Itsdangrous生成的临时票据，里面隐藏了openid
                "access_token": generate_save_user_token(openid),
            })
        else:
            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 获取oauth_user关联的user
            user = oauth_user.user
            # 只能保证不敏感的信息　user.id
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)
            return response

    def post(self, request):
        # user = QQAuthUserView(data=request.data)
        # 获取序列化器（GenericAPIView拥有get_serializer的属性　APIView没有该属性）
        serializer = self.get_serializer(data=request.data)
        # 开始校验
        serializer.is_valid(raise_exception=True)
        # 保存校验结果，并接受
        user = serializer.save()
        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        print(token)
        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })
        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)
        return response
